<?php
/**
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/9/14 14:50
 */
include_once dirname(dirname(dirname(__FILE__))) . "/common.php";
\ns_core\m_load::load_old('nn_logic/op_queue/op_queue.class.php');
\ns_core\m_load::load_old('nn_logic/clip_task/clip_task.class.php');
\ns_core\m_load::load("ns_data_model.command.m_command_task_log_inout");

class clip_task_model {

    static $mode_index = array(
        'std'=>'01',
        'hd'=>'02',
        'low'=>'03',
        '4k'=>'04',
    );

    /**
     * 根据id获取单个任务
     * @param $task_id
     * @return bool|null
     */
    static public function get_task_by_id($task_id){
        $dc = \m_config::get_dc();
        $sql = "select * from nns_mgtvbk_clip_task where nns_id='$task_id' ";
        return nl_db_get_one($sql,$dc->db());
    }

    /**
     * 更新队列任务
     * @param $task_id
     * @param $info
     * @return bool
     */
    static public function update_task($task_id,$info){
        $dc = \m_config::get_dc();
        $db = $dc->db();
        return nl_db_update($db,'nns_mgtvbk_clip_task', $info, "nns_id='".$task_id."'");
    }

    /**
     * 取切片任务
     *  取优先级权重高的任务
     * @param $sp_id
     * @return bool|null
     */
    static public function get_task($sp_id)
    {
        $dc = \m_config::get_dc();
        $db = $dc->db();
        //查询切片是否已经关闭
        $sp_config_info = m_config::_get_sp_info($sp_id);
        $sp_config = isset($sp_config_info['data_info']['nns_config']) ? $sp_config_info['data_info']['nns_config'] : null;
        if (empty($sp_config) || !isset($sp_config) || (isset($sp_config['disabled_clip'])&&(int)$sp_config['disabled_clip']===1))
        {
            return false;
        }

        //默认drm不加密
        $clip_flag_enabled = (isset($sp_config['main_drm_enabled']) && (int)$sp_config['main_drm_enabled'] == 1) ? 1 : 0;
        $sql = "select * from nns_mgtvbk_clip_task where (ISNULL(nns_state) or nns_state='' or nns_state='add' or nns_state='live_to_media_wait') and nns_org_id='{$sp_id}' order by nns_priority desc,nns_create_time asc limit 1";

        $task_info =  nl_db_get_one($sql,$db);
        if($task_info == false)
        {
            return false;
        }

        if($task_info['nns_video_type'] == 2)
        {
            $xml = self::_build_task_file_package_content($db, $task_info);
        }
        else
        {
            $b_media_exists = self::_vod_media_exists_v2($task_info, $db);
            if(!isset($b_media_exists[0]) || !is_array($b_media_exists[0]) || empty($b_media_exists[0]))
            {
                //该分集下还没有片源
                \m_config::write_clip_receive_log('当前分集下没有片源', $sp_id);
                $sql = "update nns_mgtvbk_clip_task set nns_state='cancel' where nns_id='".$task_info['nns_id']."'";
                nl_execute_by_db($sql,$db);
                return false;
            }
            $b_media_exists = $b_media_exists[0];
            $cp_config_info = \m_config::_get_cp_info($b_media_exists['nns_cp_id']);
            $cp_config = (isset($cp_config_info['data_info']['nns_config']) && !empty($cp_config_info['data_info']['nns_config'])) ? $cp_config_info['data_info']['nns_config'] : null;
            if($cp_config_info['ret'] !=0 || empty($cp_config))
            {
                return false;
            }
            if($clip_flag_enabled === 0)
            {
                $clip_flag_enabled = (isset($cp_config['main_drm_enabled']) && (int)$cp_config['main_drm_enabled'] == 1) ? 1 : 0;
            }
            $xml = self:: _build_task_content($task_info,$clip_flag_enabled,$cp_config);
        }
        if($xml===false)
        {
            return false;
        }
        $task_info['nns_content'] = $xml;
        $nns_content = htmlspecialchars($task_info['nns_content'], ENT_QUOTES);
        $sql = "update nns_mgtvbk_clip_task set nns_content='".$nns_content."' where nns_id='".$task_info['nns_id']."'";
        nl_execute_by_db($sql,$db);

        return $task_info;
    }


    /**
     * file类型获取
     * @param $db
     * @param $param
     * @return bool|string
     */
    static public function _build_task_file_package_content($db,$param)
    {
        $sql = "select * from nns_file_package where nns_id='".$param['nns_video_id']."'";
        $video_info = nl_db_get_one($sql,$db);

        $sp_config_info = m_config::_get_sp_info($param['nns_org_id']);
        $sp_config = isset($sp_config_info['data_info']['nns_config']) ? $sp_config_info['data_info']['nns_config'] : null;
        if (empty($sp_config) || !isset($sp_config))
        {
            return false;
        }

        $str_media_download_url  = (isset($sp_config['down_url']) && !empty($sp_config['down_url'])) ? $sp_config['down_url'] : '';
        if(strlen($str_media_download_url) <1)
        {
            return false;
        }
        $force = !empty($param['nns_force'])?'1':'0';
        $queue_model = new ns_model\m_queue_model();
        $query_info =  array(
            NS_CDS_FILE => array(
                'base_info' => $video_info,
            ),
        );
        $result_video_data = $queue_model->_get_cdn_epg_import_id($param['nns_org_id'], NS_CDS_FILE, $query_info);
        $video_info['nns_file_id'] = $str_media_temp_id = (isset($result_video_data['data_info']) && strlen($result_video_data['data_info']) >0) ? $result_video_data['data_info'] : $param['nns_video_id'];

        $url = $str_media_download_url.'file_id='.$video_info['nns_import_id'].'&cp_id='.$video_info['nns_cp_id'];
        $result = file_get_contents($url);
        $ret_arr = json_decode($result, true);
        if($ret_arr['err']=='1'){
            $task_log = array(
                'nns_task_id' => $param['nns_id'],
                'nns_state'   => 'get_media_url_fail',
                'nns_desc'	=> $url.'======='.$result,
            );
            self::add_task_log($task_log);
            return false;
        }
        $media_cp_id = $video_info['nns_import_source'];
        if(isset($sp_config['clip_cp_id_sent_model']) && !empty($sp_config['clip_cp_id_sent_model']))
        {
            $media_cp_id = $video_info['nns_producer'];
        }

        $video_info['nns_url'] = isset($video_info['nns_file_url']) && !empty($video_info['nns_file_url']) ? $video_info['nns_file_url'] : $video_info['nns_service_url'];
        $ret_xml  ='<task id="'.$param['nns_id'].'" force="'.$force.'" model="0" file_save_mode="'.$sp_config['upload_clip_to_ftp_enabled'].'" ftp_addr="'.$sp_config['upload_clip_to_ftp_url'].'">';
        $ret_xml .=    '<video id="'.$param['nns_file_id'].'" name="'.htmlspecialchars($video_info['nns_name'], ENT_QUOTES).'" video_type="'.$param['nns_video_type'].'" pinyin="">';
        $ret_xml .=        '<index_list>';
        $ret_xml .=            '<media_list>';
        $ret_xml .=                '<media id="'.$param['nns_file_id'].'" name="'.htmlspecialchars($param['nns_name'], ENT_QUOTES).'" file_id="'.$param['nns_import_id'].'" content_id="'.$param['nns_import_id'].'" content_url="'.$video_info['nns_url'].'" kbps_index="001" kbps="1314" md5="" drm_enabled="0" drm_encrypt_way="" cp_id="'.$media_cp_id.'" media_type="file" domain="'.$video_info['nns_domain'].'" cms_id="'.$video_info['nns_cp_id'].'"/>';
        $ret_xml .=            '</media_list>';
        $ret_xml .=        '</index_list>';
        $ret_xml .=    '</video>';
        $ret_xml .='</task>';
        return $ret_xml;
    }

    /**
     * 添加到任务log
     * $task_log array(nns_task_id,nns_state,nns_desc)
     */
    static public function add_task_log($task_log){

        $dc = \m_config::get_dc();
        $db = $dc->db();
        $task_info = self::get_task_by_id($task_log['nns_task_id']);
        \ns_core\m_load::load('ns_model.clip.clip');
        /*****************记录切片主要过程的流程日志 xinxin.deng 2018/11/14 10:40  start******************/
        $command_status= '';
        $command_reason = '';
        if (strstr($task_log['nns_state'], 'fail'))
        {
            $command_status = NS_CDS_COMMAND_CLIP_FAIL;
            $command_reason = '切片失败:' . $task_log['nns_state'];
        }
        else if ($task_log['nns_state'] == 'ok')
        {
            $command_status = NS_CDS_COMMAND_CLIP_SUCCESS;
            $command_reason = '上报成功';
        }
        else if ($task_log['nns_state'] == 'handle')
        {
            $command_status = NS_CDS_COMMAND_CLIP_HANDLE;
            $command_reason = '切片正在执行';
        }

        if (!empty($command_status))
        {
            $query_op = \nl_op_queue::query_by_id($dc, $task_info['nns_op_id']);
            $re_w_log = m_config::write_clip_execute_log("任务切片状态日志：".var_export($task_log,true), $task_info['nns_org_id'], $task_info['nns_op_id']);
            $command_task_log_params = array(
                'base_info' => array(
                    'nns_command_task_id' => $query_op['data_info'][0]['nns_command_task_id'],
                    'nns_status' => $command_status,
                    'nns_desc' => $command_reason,
                    'nns_execute_url' => $re_w_log['data_info']['base_dir'],
                )
            );
            $obj_command_task_log = new m_command_task_log_inout();
            $obj_command_task_log->add($command_task_log_params);
        }

        /*****************记录切片流程日志 xinxin.deng 2018/11/14 10:40  end******************/

        $task_log['nns_id'] = np_guid_rand();
        $task_log['nns_video_type'] = $task_info['nns_video_type'];
        $task_log['nns_video_id'] = $task_info['nns_video_id'];
        $task_log['nns_video_index_id'] = $task_info['nns_video_index_id'];
        $task_log['nns_create_time'] = date('Y-m-d H:i:s');
        $task_log['nns_create_mic_time'] = microtime(true)*10000;
        return nl_db_insert($db,'nns_mgtvbk_clip_task_log',$task_log);
    }

    static public function _vod_media_exists_v2($params,$db)
    {
        $sql = "select * from nns_vod_media where nns_id='{$params['nns_video_media_id']}' and  nns_deleted != 1 and  nns_vod_id='{$params['nns_video_id']}' and nns_vod_index_id='{$params['nns_video_index_id']}'";
        return  nl_query_by_db($sql,$db);
    }

    /**
     * 创建任务
     * @param $param
     * @param int $clip_flag_enabled
     * @param null $cp_config
     * @return bool|string
     */
    static public function _build_task_content($param,$clip_flag_enabled=0,$cp_config=null)
    {
        $dc = \m_config::get_dc();
        $db = $dc->db();
        $video_info = null;
        $video_index_info = null;
        $media_list = null;
        $video_info_type='video';
        $index_info_type='index';
        $imedia_info_type='media';
        if($param['nns_video_type']==0)
        {
            //vod
            $vod_id = $param['nns_video_id'];
            $sql = "select * from nns_vod where nns_id='".$vod_id."'";
            $video_info = nl_db_get_one($sql,$db);
            $sql = "select * from nns_vod_index where nns_id='".$param['nns_video_index_id']."'";
            $video_index_info = nl_db_get_one($sql,$db);
            $media_list = self::get_vod_media($param);
        }
        else
        {
            //live
            $live_id = $param['nns_video_id'];
            $sql = "select * from nns_live where nns_id='".$live_id."'";
            $video_info = nl_db_get_one($sql,$db);
            $sql = "select * from nns_live_index where nns_id='".$param['nns_video_index_id']."'";
            $video_index_info = nl_db_get_one($sql,$db);
            $media_list = self::get_live_media($param);
            $video_info_type='live';
            $index_info_type='live_index';
            $imedia_info_type='live_media';
        }
        $sp_config_info = m_config::_get_sp_info($param['nns_org_id']);
        $sp_config = isset($sp_config_info['data_info']['nns_config']) ? $sp_config_info['data_info']['nns_config'] : null;
        if (empty($sp_config) || !isset($sp_config))
        {
            return false;
        }

        $str_media_download_url  = (isset($sp_config['down_url']) && !empty($sp_config['down_url'])) ? $sp_config['down_url'] : '';

        if(strlen($str_media_download_url) <1)
        {
            return false;
        }

        $str_live_to_media=0;
        if($param['nns_video_type']==0 && $media_list[0]['nns_live_to_media'] == '1')
        {
            $str_live_to_media=1;
        }
        $up_ftp = '';
        if(isset($sp_config['upload_clip_to_ftp_enabled']) && $sp_config['upload_clip_to_ftp_enabled'] == '1')
        {
            $up_ftp = rtrim($sp_config['upload_clip_to_ftp_url'],"/");
            if(isset($sp_config['upload_clip_to_ftp_dir_mode']))
            {
                switch ($sp_config['upload_clip_to_ftp_dir_mode'])
                {
                    case '1': //山东有线上传到指定目录  producer+YYYYMM / nns_ext_url //针对单片源时使用
                        $vod_producer = strtoupper($video_info['nns_producer']);
                        $vod_producer_len = strlen($vod_producer);
                        $up_ftp .= "/$vod_producer" . substr(ltrim($media_list[0]['nns_ext_url']),$vod_producer_len,6) . "/" . ltrim($media_list[0]['nns_ext_url']);
                        break;
                }
            }
        }
        $force = !empty($param['nns_force'])?'1':'0';
        $ret_xml = '';
        $ret_xml .=	'<task id="'.$param['nns_id'].'" force="'.$force.'" model="0" type="'.$str_live_to_media.'" file_save_mode="'.$sp_config['upload_clip_to_ftp_enabled'].'" ftp_addr="'.$up_ftp.'">';
        if((int)$sp_config['import_id_mode'] !== 1 && (int)$sp_config['import_id_mode'] !== 3 && (int)$sp_config['import_id_mode'] !== 11)
        {
            $queue_model = new ns_model\m_queue_model();
            $query_info =  array(
                $video_info_type => array(
                    'base_info' => $video_info,
                ),
            );
            $result_video_data = $queue_model->_get_cdn_epg_import_id($param['nns_org_id'], $video_info_type, $query_info);
            $param['nns_video_id'] = $str_media_temp_id = (isset($result_video_data['data_info']) && strlen($result_video_data['data_info']) >0) ? $result_video_data['data_info'] : $param['nns_video_id'];
        }
        else
        {
            $str_media_temp_id = $param['nns_video_id'];
        }
        $ret_xml .= '<video id="'.$param['nns_video_id'].'" name="'.htmlspecialchars($video_info['nns_name'], ENT_QUOTES).'" video_type="'.$param['nns_video_type'].'" pinyin="'.htmlspecialchars($video_info['nns_pinyin'], ENT_QUOTES).'">';
        $ret_xml .=	'<index_list>';
        $i = 0;
        $flag_media_type = 'ts';
        $media_xml = '<media_list>';
        foreach($media_list as $media_info)
        {
            $url = $str_media_download_url.'file_id='.$media_info['nns_import_id'].'&cp_id='.$media_info['nns_cp_id'];
            $result = file_get_contents($url);
            $ret_arr = json_decode($result, true);
            if($ret_arr['err']=='1'){

                $task_log = array(
                    'nns_task_id' => $param['nns_id'],
                    'nns_state'   => 'get_media_url_fail',
                    'nns_desc'	=> $url.'======='.$result,
                );
                self::add_task_log($task_log);
                continue;
            }
            if(empty($media_info['nns_name']))
            {
                $media_info['nns_name'] = $video_info['nns_name'].$video_index_info['nns_index'].$media_info['nns_mode'];
            }
            $kbps_index = self::get_kbps_index($media_info['nns_mode']);
            $media_hash = self::get_media_hash($media_info['nns_import_id'],$media_info['nns_cp_id']);
            $nns_cp_id = strlen($media_info['nns_cp_id']) < 1 ? 0 : $media_info['nns_cp_id'];

            $flag_media_type = $nns_media_type = (strlen($media_info['nns_filetype']) <1) ? 'ts' : ((strtolower($media_info['nns_filetype']) == 'm3u8') ? 'hls' : $media_info['nns_filetype']);
            //修复BUG，开启了DRM加密，当片源需要加密时才切片加密，不需要则不加密
            $drm_flag_enabled = $clip_flag_enabled ? (isset($media_info['nns_drm_enabled']) ? $media_info['nns_drm_enabled'] : $media_info['nns_drm_flag']) : 0;

            $drm_encrypt_way = '';
            if($drm_flag_enabled !=0)
            {
                $cp_config_info = \m_config::_get_cp_info($media_info['nns_cp_id']);
                $cp_config = (isset($cp_config_info['data_info']['nns_config']) && !empty($cp_config_info['data_info']['nns_config'])) ? $cp_config_info['data_info']['nns_config'] : null;
                if($cp_config_info['ret'] !=0 || empty($cp_config))
                {
                    return false;
                }

                if(!isset($cp_config['main_drm_enabled']) || $cp_config['main_drm_enabled'] != 1)
                {
                    $drm_flag_enabled=0;
                }
                else
                {
                    if (isset($cp_config['q_disabled_drm']) && $cp_config['q_disabled_drm'] == 1)
                    {
                        $drm_encrypt_way='verimatrix';
                    }
                    else if (isset($cp_config['clip_drm_enabled']) && $cp_config['clip_drm_enabled'] == 1)
                    {
                        $drm_encrypt_way='taihe';
                    }
                    else if (isset($cp_config['q_marlin_drm_enable']) && $cp_config['q_marlin_drm_enable'] == 1)
                    {
                        $drm_encrypt_way='marlin';
                    }
                }
            }

            $str_clip_custom_origin_id = (isset($cp_config['clip_custom_origin_id']) && strlen($cp_config['clip_custom_origin_id']) >0) ? $cp_config['clip_custom_origin_id'] : "";
            $str_media_temp_id = $media_info['nns_id'];
            $str_index_temp_id = $video_index_info['nns_import_id'];
            $media_cp_id = $media_info['nns_import_source'];
            if(isset($sp_config['clip_cp_id_sent_model']) && !empty($sp_config['clip_cp_id_sent_model']) && $sp_config['clip_cp_id_sent_model']=='1')
            {
                $media_cp_id = $video_info['nns_producer'];
            }
            else if(isset($sp_config['clip_cp_id_sent_model']) && !empty($sp_config['clip_cp_id_sent_model']) && $sp_config['clip_cp_id_sent_model']=='2')
            {
                $media_cp_id = $video_info['nns_cp_id'];
            }
            if((int)$sp_config['import_id_mode'] !== 1 && (int)$sp_config['import_id_mode'] !== 3 && (int)$sp_config['import_id_mode'] !== 11)
            {
                $queue_model = new ns_model\m_queue_model();
                $query_info =  array(
                    NS_CDS_MEDIA => array(
                        'base_info' => $media_info,
                    ),
                );
                $result_media_data = $queue_model->_get_cdn_epg_import_id($param['nns_org_id'], NS_CDS_MEDIA, $query_info);

                $str_index_temp_id = $str_media_temp_id = (isset($result_media_data['data_info']) && strlen($result_media_data['data_info']) >0) ? $result_media_data['data_info'] : $media_info['nns_id'];
            }

            $str_live_to_media_desc='';
            if($param['nns_video_type']==0 && $media_info['nns_live_to_media'] == '1' && strlen($media_info['nns_ext_url'])>0 && self::is_json($media_info['nns_ext_url']))
            {
                $arr_nns_ext_url = json_decode($media_info['nns_ext_url'],true);
                if(isset($arr_nns_ext_url['playbill_playurls']) && !empty($arr_nns_ext_url['playbill_playurls']) && is_array($arr_nns_ext_url['playbill_playurls']))
                {
                    $str_live_to_media_desc=' voda_id="'.$arr_nns_ext_url['playbill_playurls']['nns_content_id']
                        .'" voda_start_time="'.$arr_nns_ext_url['playbill_playurls']['start_date'].' '.$arr_nns_ext_url['playbill_playurls']['start_time']
                        .'" voda_time_len="'.$arr_nns_ext_url['playbill_playurls']['duration'].'" timezone="' . $arr_nns_ext_url['playbill_playurls']['timezone'].'" ';
                }
            }
            $str_temp_domain = $media_info['nns_domain'];
            $str_temp_cms_id = $media_info['nns_cp_id'];
            if(empty($sp_config['is_starcor_telecom']) || !isset($sp_config['is_starcor_telecom']) || (int)$sp_config['is_starcor_telecom'] == 0)
            {
                $str_temp_domain = '';
                $str_temp_cms_id = '';
                //$media_cp_id = $media_info['nns_cp_id'];
            }
            /******如果上游传的是绝对路劲，那么只保留相对路劲 xinxin.deng 2018/7/30 14:04 start*****/
            if (stripos($media_info['nns_url'], 'ftp://') === true || stripos($media_info['nns_url'], 'http://') === true)
            {
                $nns_url = parse_url($media_info['nns_url']);
                $media_info['nns_url'] = $nns_url['path'];
            }
            /******如果上游传的是绝对路劲，那么只保留相对路劲 xinxin.deng 2018/7/30 14:04 end*****/

            if(stripos($media_info['nns_url'], '&') !== FALSE)
            {
                $media_info['nns_url'] = urlencode($media_info['nns_url']);
            }
            if(isset($sp_config['cdn_import_media_mode'])&&(int)$sp_config['cdn_import_media_mode']===1){
                $media_xml .= '<media id="'.$str_media_temp_id.'" name="'.htmlspecialchars($media_info['nns_name'], ENT_QUOTES).'" file_id="'.$media_info['nns_import_id'].
                    '" content_id="'.$str_index_temp_id.'" content_url="'.$media_info['nns_url'].'" kbps_index="0'.$kbps_index.'" kbps="'.$media_info['nns_kbps'].'" md5="'.
                    $media_hash.'" drm_enabled="'.$drm_flag_enabled.'" drm_encrypt_way="'.$drm_encrypt_way.'" cp_id="'.$media_cp_id.'" media_type="'.
                    $nns_media_type.'" domain="'.$str_temp_domain.'" cms_id="'.$str_temp_cms_id.'" custom_origin_id="'.$str_clip_custom_origin_id.'"'.$str_live_to_media_desc.'/>';
            }
            elseif(isset($sp_config['cdn_import_media_mode'])&&(int)$sp_config['cdn_import_media_mode']===2){
                if($media_info['nns_id']==$param['nns_video_media_id']){
                    $media_xml .= '<media id="'.$str_media_temp_id.'" name="'.htmlspecialchars($media_info['nns_name'], ENT_QUOTES).'" file_id="'.$media_info['nns_import_id'].
                        '" content_id="'.$str_index_temp_id.'" content_url="'.$media_info['nns_url'].'" kbps_index="0'.$kbps_index.'" kbps="'.$media_info['nns_kbps'].'" md5="'.
                        $media_hash.'" drm_enabled="'.$drm_flag_enabled.'" drm_encrypt_way="'.$drm_encrypt_way.'" cp_id="'.$media_cp_id.'" media_type="'.
                        $nns_media_type.'" domain="'.$str_temp_domain.'" cms_id="'.$str_temp_cms_id.'" custom_origin_id="'.$str_clip_custom_origin_id.'"'.$str_live_to_media_desc.'/>';
                }
            }
            else
            {
                if($media_info['nns_id']==$param['nns_video_media_id']){
                    $media_xml .= '<media id="'.$str_media_temp_id.'" name="'.htmlspecialchars($media_info['nns_name'], ENT_QUOTES).'" file_id="'.$media_info['nns_import_id'].
                        '" content_id="'.$str_index_temp_id.'" content_url="'.$media_info['nns_url'].'" kbps_index="0'.$kbps_index.'" kbps="'.$media_info['nns_kbps'].'" md5="'.
                        $media_hash.'" drm_enabled="'.$drm_flag_enabled.'" drm_encrypt_way="'.$drm_encrypt_way.'" cp_id="'.$media_cp_id.'" media_type="'.
                        $nns_media_type.'" domain="'.$str_temp_domain.'" cms_id="'.$str_temp_cms_id.'" custom_origin_id="'.$str_clip_custom_origin_id.'"'.$str_live_to_media_desc.'/>';
                }
            }
            $i++;
        }
        if($i==0){
            $sql = "update nns_mgtvbk_clip_task set nns_state='get_media_url_fail' where nns_id='".$param['nns_id']."'";
            nl_execute_by_db($sql, $db);
            return false;
        }
        $media_xml .= '</media_list>';
        if((int)$sp_config['import_id_mode'] !== 1 && (int)$sp_config['import_id_mode'] !== 3 && (int)$sp_config['import_id_mode'] !== 11)
        {
            $queue_model = new ns_model\m_queue_model();
            $query_info =  array(
                $index_info_type => array(
                    'base_info' => $video_index_info,
                ),
            );
            $result_index_data = $queue_model->_get_cdn_epg_import_id($param['nns_org_id'], $index_info_type, $query_info);
            $param['nns_video_index_id'] = (isset($result_index_data['data_info']) && strlen($result_index_data['data_info']) >0) ? $result_index_data['data_info'] : $param['nns_video_index_id'];
        }
        $ret_index  = '<index id="'.$param['nns_video_index_id'].'" index="'.$video_index_info['nns_index'].'" name="'.htmlspecialchars($video_index_info['nns_name'], ENT_QUOTES).'" media_type="'.$flag_media_type.'">';

        $ret_xml .=$ret_index.$media_xml;
        $ret_xml .='</index>';
        $ret_xml .=	'</index_list>';
        $ret_xml .= '</video>';
        $ret_xml .= '</task>';
        return $ret_xml;
    }

    /**
     * 获取片源
     * @param $task_info
     * @return bool
     */
    static public function get_vod_media($task_info){
        $dc = \m_config::get_dc();
        $db = $dc->db();;

        $sql = "select * " .
            " from nns_vod_media" .
            " where " .
            "  nns_vod_id='".$task_info['nns_video_id']."' " .
            " and nns_vod_index_id='".$task_info['nns_video_index_id']."'  and nns_deleted != 1 order by nns_kbps desc";
        return nl_db_get_all($sql,$db);
    }

    /**
     * 获取片源
     * @param $task_info
     * @return bool
     */
    static public function get_live_media($task_info){
        $dc = \m_config::get_dc();
        $db = $dc->db();
        $sql = "select * " .
            " from nns_live_media" .
            " where " .
            "  nns_live_id='".$task_info['nns_video_id']."' " .
            " and nns_live_index_id='".$task_info['nns_video_index_id']."'";
        return nl_db_get_all($sql,$db);
    }

    static public function get_kbps_index($mode){
        $mode= strtolower($mode);
        $mode_index = '01';
        if($mode && isset(self::$mode_index[$mode])){
            $mode_index = clip_task_model::$mode_index[$mode];
        }
        return $mode_index;
    }

    /**
     * 取片源的hash值
     * @param $media_import_id
     * @param null $nns_cp_id
     * @return string
     */
    static public function get_media_hash($media_import_id,$nns_cp_id=null)
    {
        $media_hash='';
        if(empty($media_import_id))
        {
            return $media_hash;
        }
        $nns_cp_id = (strlen($nns_cp_id) > 0) ? $nns_cp_id : 0;
        $dc = \m_config::get_dc();
        $sql="select * from nns_vod_media_ex where nns_vod_media_id='{$media_import_id}' and nns_key='file_hash' and nns_cp_id='{$nns_cp_id}' limit 1";
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result || !is_array($result) || !isset($result[0]['nns_value']))
        {
            return $media_hash;
        }
        return $result[0]['nns_value'];
    }

    static public function get_asset_id_by_sp_import_id($sp_id, $video_type, $nns_id,$cp_id=null,$sp_config = null,$mode = "cdn")
    {
        if (strlen($sp_id) < 1)
        {
            return self::return_data('1', 'sp_id为空', '');
        }
        if (strlen($video_type) < 1)
        {
            return self::return_data('1', 'video_type为空', '');
        }
        if (strlen($nns_id) < 1)
        {
            return self::return_data('1', 'nns_id为空', '');
        }
        if (!isset($sp_config) || empty($sp_config) || !is_array($sp_config))
        {
            $sp_config_info = m_config::_get_sp_info($sp_id);
            $sp_config = isset($sp_config_info['data_info']['nns_config']) ? $sp_config_info['data_info']['nns_config'] : null;
            if (empty($sp_config) || !isset($sp_config))
            {
                return self::return_data('1', '查询sp配置为空', '');
            }
        }
        $array_data = null;
        if($mode === 'epg')
        {
            $config_action = $mode . "_" . $video_type . "_import_id_mode";
        }
        else
        {
            $config_action = "import_id_mode";
        }
        if (!isset($sp_config[$config_action]) || strlen($sp_config[$config_action]) < 1 || (int)$sp_config[$config_action] < 1)
        {
            $array_data['nns_id'] = $nns_id;
            $video_info = self::get_back_info_one($video_type, $array_data);
            $last_data=array(
                'query_info'=>$array_data,
                'data_info'=>$video_info
            );
            return self::return_data(0, 'ok', $last_data);
        } //兼容-end
        else
        {
            switch ($video_type)
            {
                case 'video':
                    $str_func = 'get_vod_info';
                    $str_integer_id = 'nns_integer_id';
                    $str_import_id = 'nns_asset_import_id';
                    $import_id_model_flags = '1';
                    $import_id_model_flags_1 = '000000';
                    $import_id_model_flags_2 = '0000';
                    $import_id_model_flags_3 = '000001';
                    break;
                case 'index':
                    $str_func = 'get_vod_index_info';
                    $str_integer_id = 'nns_integer_id';
                    $str_import_id = 'nns_import_id';
                    $import_id_model_flags = '2';
                    $import_id_model_flags_1 = '001000';
                    $import_id_model_flags_2 = '0001';
                    $import_id_model_flags_3 = '000002';
                    break;
                case 'media':
                    $str_func = 'get_vod_media_info';
                    $str_integer_id = 'nns_integer_id';
                    $str_import_id = 'nns_import_id';
                    $import_id_model_flags = '3';
                    $import_id_model_flags_1 = '002000';
                    $import_id_model_flags_2 = '0002';
                    $import_id_model_flags_3 = '000003';
                    break;
                case 'live':
                    $str_func = 'get_live_info';
                    $str_integer_id = 'nns_integer_id';
                    $str_import_id = 'nns_import_id';
                    $import_id_model_flags = '4';
                    $import_id_model_flags_1 = '004000';
                    $import_id_model_flags_2 = '0004';
                    $import_id_model_flags_3 = '010001';
                    break;
                case 'live_index':
                    $str_func = 'get_live_index_info';
                    $str_integer_id = 'nns_integer_id';
                    $str_import_id = 'nns_import_id';
                    $import_id_model_flags = '5';
                    $import_id_model_flags_1 = '005000';
                    $import_id_model_flags_2 = '0005';
                    $import_id_model_flags_3 = '010002';
                    break;
                case 'live_media':
                    $str_func = 'get_live_media_info';
                    $str_integer_id = 'nns_integer_id';
                    $str_import_id = 'nns_content_id';
                    $import_id_model_flags = '6';
                    $import_id_model_flags_1 = '006000';
                    $import_id_model_flags_2 = '0006';
                    $import_id_model_flags_3 = '010003';
                    break;
                case 'playbill':
                    $str_func = 'get_playbill_info';
                    $str_integer_id = 'nns_integer_id';
                    $str_import_id = 'nns_playbill_import_id';
                    $import_id_model_flags = '7';
                    $import_id_model_flags_1 = '007000';
                    $import_id_model_flags_2 = '0007';
                    $import_id_model_flags_3 = '020001';
                    break;
                case 'file':
                    $str_func = 'get_file_package_info';
                    $str_integer_id = 'nns_integer_id';
                    $str_import_id = 'nns_import_id';
                    $import_id_model_flags = '8';
                    $import_id_model_flags_1 = '000000';
                    $import_id_model_flags_2 = '0000';
                    $import_id_model_flags_3 = '030001';
                    break;
                default:
                    return self::return_data('1', '媒资类型错误！');
            }
            $str_csp_id = defined('CSP_ID') ? CSP_ID : isset($sp_config['import_csp_id']) ? $sp_config['import_csp_id'] : '';

            switch ($sp_config[$config_action])
            {
                case '1':
                    $array_data['nns_id'] = $nns_id;
                    break;
                case '2':
                    $array_data[$str_import_id] = $nns_id;
                    break;
                case '3':
                    $array_data['nns_id'] = $nns_id;
                    break;
                case '4':
                    $arr_csp_id = explode("|", $str_csp_id);
                    $num_begin = strlen($arr_csp_id[0] . $import_id_model_flags);
                    $num_begin = $num_begin>0 ? $num_begin : 0;
                    $num_end = strlen($arr_csp_id[1]);
                    $num_end = $num_end>0 ? $num_end : 0;
                    $nns_id = substr($nns_id, $num_begin);
                    $array_data[$str_integer_id] = ($num_end >0) ? substr($nns_id, 0,-$num_end) : $nns_id;
                    break;
                case '5':
                    $num_begin = strlen($import_id_model_flags_3);
                    $num_begin = $num_begin>0 ? $num_begin : 0;
                    $array_data[$str_integer_id] = preg_replace('/^0*/', '',substr($nns_id, $num_begin));
                    break;
                case '7':
                    $array_data[$str_integer_id] = preg_replace('/^0*/', '',substr($nns_id, 10));
                    break;
                case '8': //cpid+import_id_model_flags+数字ID
                    $num_begin = strlen($cp_id) + strlen($import_id_model_flags);
                    $array_data[$str_integer_id] =  preg_replace('/^0*/', '',substr($nns_id, $num_begin));
                    break;
                default:
                    $array_data['nns_id'] = $nns_id;
            }
        }
        if(isset($cp_id) && strlen($cp_id)>0)
        {
            $array_data['nns_cp_id']=$cp_id;
        }
        $array_data['nns_deleted'] = '0';
        $video_info = self::get_back_info_one($video_type,$array_data);
        $last_data=array(
            'query_info'=>$array_data,
            'data_info'=>$video_info
        );
        return self::return_data(0, 'ok', $last_data);
    }

    /**
     * 获取媒资信息
     * @param $video_type
     * @param $array_query
     * @return bool
     */
    static public function get_back_info_one($video_type,$array_query)
    {
        if(!is_array($array_query) || empty($array_query))
        {
            return true;
        }
        $dc = \m_config::get_dc();
        $db = $dc->db();
        switch ($video_type)
        {
            case 'video':
                $table_name="nns_vod";
                break;
            case 'index':
                $table_name="nns_vod_index";
                break;
            case 'media':
                $table_name="nns_vod_media";
                break;
            case 'live':
                $table_name="nns_live";
                break;
            case 'live_index':
                $table_name="nns_live_index";
                break;
            case 'live_media':
                $table_name="nns_live_media";
                break;
            case 'playbill':
                $table_name="nns_live_playbill_item";
                break;
            case 'file':
                $table_name="nns_file_package";
                break;
            default:
                return true;
        }
        $sql="select * from {$table_name} where ";
        foreach ($array_query as $key=>$val)
        {
            $sql.=" {$key}='{$val}' and ";
        }
        $sql=substr(trim($sql), 0,-3)." limit 1";
        $result = nl_query_by_db($sql, $db);
        if(!$result)
        {
            return false;
        }
        return (isset($result['0']) && is_array($result['0']) && !empty($result['0'])) ? $result['0'] : true;
    }

    /**
     * @param int $ret 状态码
     * @param string $reason 状态描述
     * @param null $data 返回信息
     * @return array
     */
    public static function return_data($ret = 1, $reason = "unknown error", $data = NULL)
    {
        return array (
            'ret' => $ret,
            'reason' => $reason,
            'data_info' => ($data != NULL) ? $data : NULL
        );
    }

    /**
     * 通过切片任务ID批量获取片源、分集、主媒资注入ID
     * @param array $task_id 任务ID组  array($task_id,$task_id)
     * @return array
     * @date 2016-04-01
     * @author zhiyong.luo
     */
    static public function get_import_id_by_task_id($dc,$task_id,$sp_id)
    {
        if(!is_array($task_id) || empty($task_id))
        {
            return false;
        }
        $sql = "select c.nns_id,v.nns_cp_id,v.nns_asset_import_id as video_import_id,v.nns_name,
			i.nns_import_id as index_import_id,m.nns_import_id as media_import_id,m.nns_cp_id as media_cp_id  
			from nns_mgtvbk_clip_task as c,nns_vod as v,nns_vod_index as i,nns_vod_media as m 
			where c.nns_video_id=v.nns_id and c.nns_video_index_id=i.nns_id and 
			c.nns_video_media_id=m.nns_id and v.nns_deleted!=1 and i.nns_deleted!=1 and m.nns_deleted!=1 ";
        $task_id_strs = implode("','", $task_id);
        $sql .= "and c.nns_id in ('{$task_id_strs}') and c.nns_org_id='{$sp_id}'";
        return nl_query_by_db($sql, $dc->db());
    }


    /**
     * 更新切片后得切片队列和片源信息
     * @param $task_id
     * @param null $nns_date
     * @param null $nns_new_dir
     * @param null $nns_path
     * @param null $nns_file_size
     * @param null $nns_file_md5
     * @param null $nns_cdn_policy
     * @param null $nns_node_id
     * @param null $nns_list_ids
     * @param null $arr_sp_config
     */
    static public function q_clip_ok_push($task_id, $nns_date = null, $nns_new_dir = null, $nns_path = null, $nns_file_size = null, $nns_file_md5 = null, $nns_cdn_policy = null, $nns_node_id = null, $nns_list_ids = null,$arr_sp_config=null)
    {
        set_time_limit(0);
        $dc = \m_config::get_dc();
        $db = $dc->db();
        $sql = "select * from nns_mgtvbk_clip_task where nns_id='$task_id'";
        $clip_info = nl_db_get_one($sql, $db);
        if (is_array($clip_info) && $clip_info != null)
        {
            if (empty($nns_date))
            {
                $nns_date = $clip_info['nns_date'];
            }
            $sql_media = "select * from nns_vod_media where nns_id='{$clip_info['nns_video_media_id']}' limit 1";
            $media_info = nl_db_get_one($sql_media, $db);
            if (isset($media_info['nns_cp_id']) && $media_info['nns_cp_id'] == 'manual_import_pc')
            {
                $nns_path = 'manual_import/' . $nns_path;
            }

            $ext_data = array(
                'url' => $nns_path,
                'path' => $nns_path,
                'size' => $nns_file_size,
                'clip_id' => $task_id,
                'clip_date' => $nns_date,
                'file_md5' => $nns_file_md5,
                'policy' => $nns_cdn_policy,
                'node_id' => $nns_node_id,
                'list_ids' => $nns_list_ids
            );

            $op_id = $clip_info['nns_op_id'];
            //处理json之后中文转码的问题 feijian.gao -->start
            $ext_data_info = json_encode($ext_data, JSON_UNESCAPED_UNICODE);
            //处理json之后中文转码的问题 feijian.gao -->end
            $sql = "update nns_mgtvbk_op_queue set nns_ex_data='" . $ext_data_info . "' where nns_id='{$op_id}'";

            nl_execute_by_db($sql, $db);

            $str_set = '';

            if (is_array($media_info))
            {
                $nns_file_size = (int)$nns_file_size > 0 ? (int)$nns_file_size : 0;
                $media_info['nns_file_size'] = $media_info['nns_file_size'] > 0 ? $media_info['nns_file_size'] : 0;
                $temp_file_size = $nns_file_size > 0 ? $nns_file_size : $media_info['nns_file_size'];
                $temp_file_size = $temp_file_size > 0 ? $temp_file_size : 8080;
                $str_set .= ",nns_file_size='{$temp_file_size}'";
            }
            if(isset($arr_sp_config['clip_set_playurl']) && strlen($arr_sp_config['clip_set_playurl']) >0)
            {
                $arr_sp_config['clip_set_playurl'] = trim(rtrim(rtrim($arr_sp_config['clip_set_playurl'],'/'),'\\'));
                $temp_nns_path = trim(ltrim(ltrim($nns_path,'/'),'\\'));
                $arr_playurl = array(
                    'play_url'=>$arr_sp_config['clip_set_playurl'].'/'.$temp_nns_path,
                );
                $str_playurl = json_encode($arr_playurl);
                $str_set .= ",nns_ext_url='{$str_playurl}'";
            }
            //新增修改片源扩展信息
            $media_sql = "update nns_vod_media set nns_ext_info='" . $ext_data_info . "'{$str_set} where nns_id='{$clip_info['nns_video_media_id']}'";
            nl_execute_by_db($media_sql, $db);
        }
        unset($db);
        return true;
    }


    /**
     * 上报更新中心同步指令
     * @param $dc
     * @param $task_id
     * @param $update_params
     * @return array
     */
    static public function task_progress($dc, $task_id, $update_params)
    {
        $q_clip_task = \nl_clip_task::query_by_id($dc, $task_id);
        if ($q_clip_task != 0 || empty($q_clip_task['data_info']) || !is_array($q_clip_task['data_info']))
        {
            self::return_data(NS_CDS_FAIL, '查询切片指令队列失败');
        }
        $re_execute = \nl_op_queue::edit($dc, $update_params, $q_clip_task['data_info']['nns_op_id']);
        if ($re_execute['ret'] == 0)
        {
            return self::return_data(NS_CDS_SUCCE, '更新中心同步指令队列成功');
        }
        else
        {
            return self::return_data(NS_CDS_FAIL, '更新中心同步指令队列失败');
        }
    }


    /**
     * 处理删除切片队列的片源
     * @param $task_id
     * @return bool
     */
    static public function can_delete_clip_file_new($task_id){
        $dc = \m_config::get_dc();
        $db = $dc->db();
        $sql = "SELECT * FROM `nns_mgtvbk_clip_task` where `nns_id`='".$task_id."'";
        $result = nl_db_get_one($sql,$db);
        if(empty($result)){
            return true;
        }
        if(is_array($result)&&$result!=null){
            $sql_op = "SELECT * FROM `nns_mgtvbk_op_queue` where `nns_id`='".$result['nns_op_id']."'";
            $result_op = nl_db_get_one($sql_op,$db);
            if(empty($result_op)){
                return true;
            }

            if(is_array($result_op)&&$result_op!=null){
                return false;
            }
        }
        return true;
    }
}